<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NButton,
  NCheckbox,
  NCheckboxGroup,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NSpace,
  NSwitch,
  NTag,
  NPopconfirm,
  NLayout,
  NLayoutSider,
  NLayoutContent,
  NTreeSelect,
  useMessage,
  NFlex,
  NAvatar,
  NSelect,
  NUpload,
} from 'naive-ui'
import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import { formatDate, renderIcon } from '@/utils'
import { useCRUD } from '@/composables'
import api from '@/api'
import TheIcon from '@/components/icon/TheIcon.vue'
import { router } from '@/router'

defineOptions({ name: '门店配置' })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const base_path = import.meta.env.VITE_BASE
import default_image from '@/assets/images/mz.jpg'

const {
  modalVisible,
  modalTitle,
  modalAction,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '门店',
  initForm: {},
  doCreate: api.createSettingSpace,
  doUpdate: api.updateSettingSpace,
  doDelete: api.deleteSettingSpace,
  refresh: () => $table.value?.handlerefresh(),
})

const data = reactive({
  TypeData: [
    {
      label: '实体',
      value: 1,
    },
    {
      label: '虚拟',
      value: 2,
    },
  ],
  CityData: [],
  parentData: [],
  fileListLength: 0,
  dateOptions: [],
})

onMounted(() => {
  api.getSettingCity().then((res) => (data.CityData.value = res.data))
  $table.value?.handleSearch()
})
const columns = [
  {
    title: 'ID',
    key: 'id',
    width: 30,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '名称',
    key: 'name',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
    fixed: 'left',
  },
  {
    title: '英文名称',
    key: 'english_name',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
    fixed: 'left',
  },
  {
    title: '排序',
    key: 'sort',
    width: 30,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '类别',
    key: 'type',
    align: 'center',
    width: 60,
    ellipsis: { tooltip: true },
    render(row) {
      return h(
        NTag,
        { type: 'primary', size: 'small', bordered: false, style: { margin: '2px 3px' } },
        { default: () => (row.type == 1 ? '实体门店' : '虚拟门店') }
      )
    },
  },
  {
    title: '封面图',
    key: 'picture',
    width: 40,
    align: 'center',
    ellipsis: { tooltip: true },
    render(row) {
      return h(NFlex, {}, [
        h(NAvatar, {
          src: row.picture,
          width: 30,
          fallbackSrc: default_image,
        }),
      ])
    },
  },
  {
    title: '状态',
    key: 'status',
    width: 50,
    align: 'center',
    render(row) {
      return h(NSwitch, {
        size: 'small',
        rubberBand: false,
        value: row.status,
        loading: !!row.publishing,
        checkedValue: true,
        uncheckedValue:false ,
        onUpdateValue: () => handleUpdateDisable(row),
      })
    },
  },
  {
    title: '操作',
    key: 'actions',
    width: 80,
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
        withDirectives(
          h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              style: 'margin-right: 8px;',
              onClick: () => {
                on_edit(row)
              },
            },
            {
              default: () => '编辑',
              icon: renderIcon('material-symbols:edit', { size: 16 }),
            }
          ),
          [[vPermission, 'post/api/content/contents/update']]
        ),
        h(
          NPopconfirm,
          {
            onPositiveClick: () => handleDelete({ data_id: row.id }, false),
            onNegativeClick: () => {},
          },
          {
            trigger: () =>
              withDirectives(
                h(
                  NButton,
                  {
                    size: 'small',
                    type: 'error',
                  },
                  {
                    default: () => '删除',
                    icon: renderIcon('material-symbols:delete-outline', { size: 16 }),
                  }
                ),
                [[vPermission, 'delete/api/content/contents/delete']]
              ),
            default: () => h('div', {}, '确定删除该数据吗?'),
          }
        ),
      ]
    },
  },
]
// 修改用户禁用状态
async function handleUpdateDisable(row) {
  if (!row.id) return
  row.publishing = true
  row.status = row.status === false ? true : false
  row.publishing = false
  try {
    await api.updateSettingSpace(row)
    $message?.success(row.status ? '正常' : '禁用')
    $table.value?.handleSearch()
  } catch (err) {
    // 有异常恢复原来的状态
    row.status = row.status === false
  } finally {
    row.publishing = false
  }
}
//跳转路径
function on_add() {
  router.push('/appointment/settings/space_add')
}
function on_edit(row) {
  router.push({ path: '/appointment/settings/space_add', query: { id: row.id } })
}
</script>

<template>
  <NLayout has-sider wh-full>
    <NLayoutContent>
      <CommonPage show-footer title="门店列表">
        <template #action>
          <NButton
            v-permission="'post/api/content/contents/create'"
            type="primary"
            @click="on_add"
          >
            <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />新建门店
          </NButton>
        </template>
        <!-- 表格 -->
        <CrudTable
          ref="$table"
          v-model:query-items="queryItems"
          :columns="columns"
          :get-data="api.getSettingSpace"
          :scroll-x="1200"
        >
          <template #queryBar>
            <QueryBarItem label="名称" :label-width="40">
              <NInput
                v-model:value="queryItems.name"
                clearable
                type="text"
                placeholder="请输入名称"
                @keypress.enter="$table?.handleSearch()"
              />
            </QueryBarItem>

          </template>
        </CrudTable>

      </CommonPage>
    </NLayoutContent>
  </NLayout>
  <!-- 业务页面 -->
</template>
